# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
from odoo.exceptions import UserError


class MrpProduction(models.Model):
    _inherit = 'mrp.production'
    department_id=fields.Many2one('hr.department')
    move_raw_pick_ids = fields.One2many(string=u'领料单', comodel_name='stock.move', inverse_name='raw_pick_production_id')
    post_visible = fields.Boolean(
        'Allowed to Post Inventory', compute='_compute_post_visible',store=True,
        help='Technical field to check when we can post')


    @api.depends('move_finished_ids.quantity_done', 'move_finished_ids.state', 'is_locked')
    def _compute_post_visible(self):
        for order in self:
            order.post_visible = order.is_locked and any((x.quantity_done > 0 and x.state not in ['done', 'cancel']) for x in order.move_finished_ids)

    consume_line_ids = fields.One2many('mrp.consume.line','production_id',string=u'备料明细')
    max_output_qty=fields.Float(compute='compute_max_output_qty')
    def compute_max_output_qty(self):
        for record in self:
            record.max_output_qty=min(line.max_output_qty for line in record.consume_line_ids)

    can_output_qty = fields.Float(compute='compute_can_output_qty')

    def compute_can_output_qty(self):
        for record in self:
            record.can_output_qty = min(line.can_output_qty for line in record.consume_line_ids)


    def action_scarp(self):
        return {
            'view_type': 'form',
            'res_model': 'mrp.scrap.wizard',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'context': {'default_production_id': self.id}
        }

    def button_mark_done(self):
        self.ensure_one()
        self._check_company()
        for wo in self.workorder_ids:
            if wo.time_ids.filtered(lambda x: (not x.date_end) and (x.loss_type in ('productive', 'performance'))):
                raise UserError(_('Work order %s is still running') % wo.name)
        self._check_lots()

        # Moves without quantity done are not posted => set them as done instead of canceling. In
        # case the user edits the MO later on and sets some consumed quantity on those, we do not
        # want the move lines to be canceled.
        row_move_ids=self.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel'))
        if row_move_ids:
            raise UserError('有未完成的領料单请先完成再结单')
        if self.get_repicking_pickings().filtered(lambda x: x.state not in ('done', 'cancel')):
            raise UserError('有未完成的补料单请完成后再结单')
        if self.get_return_picking().filtered(lambda x: x.state not in ('done', 'cancel')):
            raise UserError('有未完成的退料单请完成后再结单')
        if self.get_scarp_pickings().filtered(lambda x: x.state not in ('done', 'cancel')):
            raise UserError('有未完成的报废单请完成后再结单')
        if self.move_finished_ids.filtered(lambda x: x.state not in ('done', 'cancel')):
            raise UserError('有未完成的入库单，请入库后再结单')

        return self.write({'date_finished': fields.Datetime.now()})



    def get_pick_moves(self, moves=False, force_update=False):
        """
        获取领料单的move
        :return:
        """
        self.ensure_one()
        picking_moves=self.env['stock.move'].search([('id','in',self.move_raw_ids.move_orig_ids.ids)])
        # if not self.move_raw_pick_ids or moves or force_update:
        #     picking_moves = self.env['stock.move'].search(
        #         [('move_dest_id', 'in', moves.ids if moves else self.move_raw_ids.ids),
        #          ('re_picking_production_id', '=', False)])  # 领料
        # else:
        #     picking_moves = self.move_raw_pick_ids
        return picking_moves


    @api.depends('move_raw_ids')
    def _compute_consume_line_ids(self):
        consume_lines = self.env['mrp.consume.line']
        for mo in self:
            lines = consume_lines.search([('production_id', '=', mo.id)])
            product_ids = mo.move_raw_ids.mapped('product_id')
            exist_product_ids = lines.mapped('product_id')
            left_products = product_ids - exist_product_ids
            consume_l = self.env['mrp.consume.line']
            for product_id in left_products:
                consume_l += self._create_consume_line(product_id, mo)

            mo.consume_line_ids = consume_l | lines

    def _create_consume_line(self, product_id, mo):
        return self.env['mrp.consume.line'].create({
            'product_id': product_id.id,
            'production_id': mo.id
        })

    # 查看领料
    def action_view_pick_picking(self):

        return self.view_picking(self.get_pick_pickings())

    # 备料
    def action_view_prepare_picking(self):

        return self.view_picking(self.get_prepare_pickings())

    # 产成品入库
    def action_view_inventory_picking(self):

        return self.view_picking(self.get_inventory_pickings())

    def action_view_scarp(self):
        return self.view_picking(self.get_scarp_pickings())

    def action_view_re_picking(self):
        return self.view_picking(self.get_repicking_pickings())
    def view_picking(self, pickings):
        action = self.env.ref('stock.action_picking_tree_all').read()[0]

        if len(pickings) > 1:
            action['domain'] = [('id', 'in', pickings.ids)]
        elif len(pickings) == 0:
            action['domain'] = [('id', 'in', [])]
        elif pickings:
            action['views'] = [(self.env.ref('stock.view_picking_form').id, 'form')]
            action['res_id'] = pickings.id
        return action
    def get_repicking_pickings(self):
        self.ensure_one()
        picking_ids = self.env['stock.picking'].search([('re_picking_production_id', 'in', self.ids)])  # 补料
        return picking_ids

    output_qty=fields.Float(string=u'产出数量',compute='compute_output_qty')

    def compute_output_qty(self):
        for r in self:
            r.output_qty=sum(r.finished_move_line_ids.mapped('qty_done'))

    def check_max_qty_done(self):
        pass



    def get_return_picking(self):
        picking_ids = self.env['stock.picking'].search([('return_raw_production_id', 'in', self.ids)])  # 退料
        return picking_ids

    def get_scarp_pickings(self):
        picking_ids = self.env['stock.picking'].search([('scarp_production_id', 'in', self.ids)])  # 报废
        return picking_ids

    repicking_count=fields.Integer(compute='compute_repicking_count')
    return_count=fields.Integer(compute='compute_repicking_count')
    scarp_count=fields.Integer(compute='compute_repicking_count')

    def compute_repicking_count(self):
        for r in self:
            if r.get_repicking_pickings():
                r.repicking_count=len(r.get_repicking_pickings())
            else:
                r.repicking_count=0
            if r.get_return_picking():
                r.return_count=len(r.get_return_picking())
            else:
                r.return_count=0
            if r.get_scarp_pickings():
                r.scarp_count=len(r.get_scarp_pickings())
            else:
                r.scarp_count=0

    # 补料
    def action_re_picking(self):
        self.ensure_one()
        return {
            'view_type': 'form',
            'res_model': 'mrp.repicking.wizard',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'context': {'re_picking_production_id': self.id, 'default_production_id': self.id}
        }

    # 退料
    def action_return(self):
        self.ensure_one()
        return {
            'view_type': 'form',
            'res_model': 'mrp.return.raw.wizard',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'context': {'return_raw_production_id': self.id, 'default_production_id': self.id}
        }

    # 报废
    def action_scrap(self):
        self.ensure_one()
        return {
            'view_type': 'form',
            'res_model': 'mrp.scrap.wizard',
            'type': 'ir.actions.act_window',
            'view_mode': 'form',
            'target': 'new',
            'context': {'scrap_production_id': self.id, 'default_production_id': self.id}
        }

    def action_view_return(self):
        return self.view_picking(self.get_return_picking())
    @api.model
    def create(self, vals_list):
        res=super(MrpProduction, self).create(vals_list)
        res._compute_consume_line_ids()
        return res
